<?php
/**************************************
 *
 * @services 服务层~主要进行数据筛选与过滤
 *
 **************************************/
namespace app\common\services;

use app\common\repositories\UserRepositories;
use GuzzleHttp\Client;
use think\config;
use think\Env;
use  think\Cache;
use think\Validate;
use think\Db;

class UserServices
{
    protected $UserRepositories;

    protected $fileName = 'AppkeyConfig.php';

    protected $wechatSessionUrl = 'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code';

    public function __construct()
    {
        $this->UserRepositories = new UserRepositories();
    }
    /**
     * 利用code获取session_key以及openid
     *
     * @param $request
     * @return mixed
     */
    public function getWechatInfoByCode($request)
    {
        $fileName = $this->fileName;
        $apikeyconfig = Config::load(APP_PATH.'/common/config/'.$fileName);
        $wxconfig = $apikeyconfig['xcxappkey'];

        $url = sprintf($this->wechatSessionUrl, $wxconfig['appId'], $wxconfig['appSecret'], $request['code']);
        $res = $this->http_get($url);
        return $res;
        if (!is_array($res)) {
            return false;
        } else {
            return $res;
        }
    }

    public function http_get($url)
    {
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
        $tmpInfo = curl_exec($curl);     //返回api的json对象
        //关闭URL请求
        curl_close($curl);
        return $tmpInfo;    //返回json对象
    }


    /**
     * 注册用户
     *
     * @param array $data
     * @param int $appid
     *
     * @return mixed
     */
    public function regist($data, $request_data)
    {
         return $this->UserRepositories->regist($data, $request_data);
    }

    /*
     *  验证登陆
     */
    public function checkLogin($sessionKey)
    {

        $userInfo = Cache::get($sessionKey);
        if ($userInfo) {
            return $userInfo;
        } else {
            return false;
        }
    }

    //保存验证码
    public function saveCode($data)
    {
        $data['create_time'] = time();
        Db::name('sms_log')->insert($data);
    }

    /*
     *  添加订单
     */
    public function addOrder($data)
    {
        $time = date('Y-m-d', time());
        $a = Cache::get($time);
        if (!$a) {
            Cache::set($time, 1, 3600 * 24);
        }else{
            Cache::inc($time);
        }
        return $this->UserRepositories->addOrder($data);
    }

    /**
     * 返回微信数组结果
     */
    public function getWeChatApiResult($result)
    {
        return json_decode($result, true);
    }

    //用户主页
    public function userInfo($param)
    {
        return $this->UserRepositories->userInfo($param);
    }

    //近期阅读
    public function nearRead($param)
    {
        return $this->UserRepositories->nearRead($param);
    }

    //我喜欢的文章
    public function likeAtr($param)
    {
        return $this->UserRepositories->likeAtr($param);
    }
    //点赞功能
    public function click($param)
    {
        $validate = new Validate([
            'sign'  => 'require',
            'id'  => 'require',
            'click' => 'require',
        ]);
        if (!$validate->check($param)) {
            return $validate->getError();
        }
        //用户已保存数据
        if ($param['sign'] == 'daily') {
            $msg = $this->UserRepositories->clickDaily($param);
            if (is_array($msg)) {
                if (!empty($msg)) {
                    return $msg;
                }
            } else {
                return 400;
            }
        }
        //编辑公共数据点赞
        if ($param['sign'] == 'edits') {
            $msg = $this->UserRepositories->clickEdits($param);
            if (is_array($msg)) {
                if (!empty($msg)) {
                    return $msg;
                } else {
                    return 400;
                }
            }
        }
    }

    /*
     *  鉴黄接口
     */
    public function syncRequest ($url = '')
    {
        include __VENDOR__.'kamYellow/php/aliyuncs/aliyun-php-sdk-core/Config.php';
        date_default_timezone_set("PRC");
        $path = __VENDOR__.'kamYellow/php/aliyun.ak.ini';
        $ak = parse_ini_file($path);
//请替换成你自己的accessKeyId、accessKeySecret
        $iClientProfile = \DefaultProfile::getProfile("cn-shanghai", $ak["accessKeyId"], $ak["accessKeySecret"]); // TODO
        \DefaultProfile::addEndpoint("cn-shanghai", "cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
        $client = new \DefaultAcsClient($iClientProfile);
        $request = new Green\ImageSyncScanRequest();
        $request->setMethod("POST");
        $request->setAcceptFormat("JSON");

        $task1 = array('dataId' =>  uniqid(),
                       'url' => $url,
                       'time' => round(microtime(true)*1000)
        );
        $request->setContent(json_encode(array("tasks" => array($task1),
                                               "scenes" => array("porn"))));
        try {
            $response = $client->getAcsResponse($request);
            if(200 == $response->code){
                $taskResults = $response->data;
                foreach ($taskResults as $taskResult) {
                    if(200 == $taskResult->code){
                        $sceneResults = $taskResult->results;
                        foreach ($sceneResults as $sceneResult) {
                            return $sceneResult->label;
                        }
                    }else{
                        return ['label' => null, 'status' => 201];
                    }
                }
            }else{
                return ['label' => null, 'status' => $response->code];
            }
        } catch (Exception $e) {
            print_r($e);
        }
    }
}